<template>
  <div class="flex h-[calc(100vh-100px)]">
    <!-- 右侧内容区 -->
    <div class="flex-1 overflow-hidden pl-4 flex flex-col">
      <!-- 可滚动的列表区域 -->
      <el-scrollbar class="flex-1">
        <ContentWrap class="h-full flex flex-col">
          <el-table
            v-loading="loading"
            :data="list"
            :show-overflow-tooltip="true"
            :stripe="true"
            class="flex-1"
          >
            <el-table-column align="center" label="序号" type="index" width="60" />
            <el-table-column align="center" label="项目编号" prop="projectNo" />
            <el-table-column align="center" label="状态" prop="status">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.PROJECT_STATUS" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="受检单位" prop="receivingUnit" />
            <el-table-column align="center" label="委托单位" prop="companyName" />
            <el-table-column align="center" label="紧急程度" prop="urgencyLevel">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.URGENCY_DEGREE" :value="scope.row.urgencyLevel" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="项目类型" prop="projectType" />
            <el-table-column align="center" label="项目负责人" prop="projectManager" />
            <el-table-column
              :formatter="dateFormatter"
              align="center"
              label="创建时间"
              prop="createTime"
              show-overflow-tooltip
              width="180px"
            />
            <el-table-column align="center" fixed="right" label="操作" width="300">
              <template #default="scope">
                <div class="flex justify-center flex-wrap gap-2">
                  <!--                  <el-button link type="primary" @click="handleStartSurvey(scope.row)">-->
                  <!--                    开始调查-->
                  <!--                  </el-button>-->
                  <!--                  <el-button-->
                  <!--                    v-hasPermi="['dk:project:survey']"-->
                  <!--                    link-->
                  <!--                    type="primary"-->
                  <!--                    @click="openAssignForm(scope.row, 'survey')"-->
                  <!--                  >-->
                  <!--                    调查分配-->
                  <!--                  </el-button>-->
                  <!--                  <el-button-->
                  <!--                    v-hasPermi="['dk:project:sample']"-->
                  <!--                    link-->
                  <!--                    type="primary"-->
                  <!--                    @click="openAssignForm(scope.row, 'sample')"-->
                  <!--                  >-->
                  <!--                    采样分配-->
                  <!--                  </el-button>-->
                  <!--                  <el-button-->
                  <!--                    v-hasPermi="['dk:project:update']"-->
                  <!--                    link-->
                  <!--                    type="primary"-->
                  <!--                    @click="openForm('update', scope.row.id)"-->
                  <!--                  >-->
                  <!--                    编辑-->
                  <!--                  </el-button>-->
                  <!--                  <el-button-->
                  <!--                    v-hasPermi="['dk:project:delete']"-->
                  <!--                    link-->
                  <!--                    type="danger"-->
                  <!--                    @click="handleDelete(scope.row.id)"-->
                  <!--                  >-->
                  <!--                    删除-->
                  <!--                  </el-button>-->
                  <el-button link type="primary" @click="planReview(scope.row)">
                    方案审核
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="mt-4">
            <Pagination
              v-model:limit="queryParams.pageSize"
              v-model:page="queryParams.pageNo"
              :total="total"
              @pagination="getList"
            />
          </div>
        </ContentWrap>
      </el-scrollbar>
    </div>

    <!-- 方案审核抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :before-close="() => (drawerVisible = false)"
      :destroy-on-close="true"
      :size="800"
      append-to-body
      custom-class="centered-drawer"
      direction="rtl"
      title="现场采样/测量计划审核"
    >
      <div class="drawer-content clear-bg">
        <!-- 项目基本信息 -->
        <div class="info-section card-block">
          <div class="info-header block-title">
            <el-icon>
              <Document />
            </el-icon>
            <span>项目信息</span>
          </div>
          <div class="info-content">
            <div class="info-item">
              <span class="label">项目编号：</span>
              <span class="value">{{ currentProject?.projectNo }}</span>
            </div>
            <div class="info-item">
              <span class="label">委托单位：</span>
              <span class="value">{{ currentProject?.companyName }}</span>
            </div>
          </div>
        </div>

        <!-- 审核表单 -->
        <div class="review-form card-block">
          <div class="form-header block-title">
            <el-icon>
              <Check />
            </el-icon>
            <span>审核内容</span>
          </div>
          <el-form ref="formRef" :model="reviewForm" label-position="top" size="small">
            <div class="review-table">
              <div class="review-table-header">
                <div class="review-table-cell cell-content">审核内容</div>
                <div class="review-table-cell cell-result">审核结果</div>
                <div class="review-table-cell cell-opinion">审核意见</div>
              </div>
              <div v-for="(item, idx) in reviewForm.items" :key="idx" class="review-table-row">
                <div class="review-table-cell cell-content">{{ item.label }}</div>
                <div class="review-table-cell cell-result">
                  <el-radio-group v-model="item.result">
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                </div>
                <div class="review-table-cell cell-opinion">
                  <el-input v-model="item.opinion" placeholder="请输入审核意见" size="small" />
                </div>
              </div>
              <!-- 其他 -->
              <div class="review-table-row">
                <div class="review-table-cell cell-content">其他</div>
                <div class="review-table-cell cell-result"></div>
                <div class="review-table-cell cell-opinion">
                  <el-input
                    v-model="reviewForm.remarks"
                    :rows="2"
                    placeholder="请输入其他"
                    size="small"
                    type="textarea"
                  />
                </div>
              </div>
            </div>
          </el-form>
        </div>

        <!-- 审核意见 -->
        <div class="review-result card-block">
          <div class="result-header block-title">
            <el-icon>
              <CircleCheck />
            </el-icon>
            <span>审核人意见</span>
          </div>
          <el-form-item>
            <el-input
              v-model="reviewForm.opinion"
              :rows="3"
              class="review-textarea"
              placeholder="请输入审核人总体意见"
              type="textarea"
            />
          </el-form-item>
        </div>

        <!-- 签名区域 -->
        <div class="signature-section card-block">
          <div class="signature-header block-title">
            <span>审核人签名</span>
          </div>
          <div class="signature-content">
            <div class="signature-item">
              <span class="label">签名：</span>
              <span class="value signature-placeholder">{{
                reviewForm.reviewer || '________________'
              }}</span>
            </div>
            <div class="signature-item">
              <span class="label">日期：</span>
              <span class="value">{{ reviewForm.reviewDate || formatCurrentDate() }}</span>
            </div>
          </div>
        </div>

        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitReview">提 交</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { ProjectApi, ProjectVO } from '@/api/dk/project'
import { onMounted, reactive, ref } from 'vue'
import { Check, CircleCheck, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

/** 项目 列表 */
defineOptions({ name: 'ProjectList' })

const loading = ref(true) // 列表的加载中
const list = ref<ProjectVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

// 修改 queryParams 的类型定义
interface QueryParams {
  pageNo: number
  pageSize: number
  companyName?: string
  projectType?: string
  projectManager?: string
  urgencyLevel?: string
  completionDate?: string[]
  receivingUnit?: string
  receivingAddress?: string
  contactPerson?: string
  contactPhone?: string
  taskSource?: string
  contractNumber?: string
  projectNo?: string
  projectName?: string
  businessPerson?: string
  businessPhone?: string
  status?: string
  contractDate?: string[]
  remarks?: string
  createTime?: string[]
  materialClassId?: number
}

const queryParams = reactive<QueryParams>({
  pageNo: 1,
  pageSize: 10,
  status: '4',
  companyName: undefined,
  projectType: undefined,
  projectManager: undefined,
  urgencyLevel: undefined,
  completionDate: [],
  receivingUnit: undefined,
  receivingAddress: undefined,
  contactPerson: undefined,
  contactPhone: undefined,
  taskSource: undefined,
  contractNumber: undefined,
  projectNo: undefined,
  projectName: undefined,
  businessPerson: undefined,
  businessPhone: undefined,
  contractDate: [],
  remarks: undefined,
  createTime: [],
  materialClassId: undefined
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 同时获取列表数据和状态统计
    const [listData] = await Promise.all([
      ProjectApi.getProjectPage({
        ...queryParams
      })
    ])
    list.value = listData.list
    total.value = listData.total
  } finally {
    loading.value = false
  }
}

// 抽屉相关变量
const drawerVisible = ref(false)
const currentProject = ref<ProjectVO>()
const formRef = ref()

// 审核表单数据
const reviewForm = reactive({
  items: [
    {
      label: '采样/测量计划内容是否全面',
      result: true,
      opinion: ''
    },
    {
      label: '采样/测量范围是否与指委托文件规定是否一致',
      result: true,
      opinion: ''
    },
    {
      label: '检测项目是否全面',
      result: true,
      opinion: ''
    },
    {
      label: '检测项目对应的空气采集器、采样/测量设备和样品保存方法与时限是否正确',
      result: true,
      opinion: ''
    },
    {
      label: '采样/测量时机、数量、方式、时间等是否符合标准、规范要求',
      result: true,
      opinion: ''
    }
  ],
  remarks: '',
  opinion: '',
  reviewer: '',
  reviewDate: ''
})

/** 方案审核抽屉 */
const planReview = async (row: ProjectVO) => {
  currentProject.value = row
  drawerVisible.value = true

  // 调用获取审核数据接口
  const response = await ProjectApi.getSurveyReview(currentProject.value?.id)

  // 检查是否有返回surveyReview数据，如果有则更新表单
  if (response && response.surveyReview) {
    const { surveyReview } = response

    // 更新表单数据
    reviewForm.items = surveyReview.items || reviewForm.items // 保留默认值如果API没返回
    reviewForm.remarks = surveyReview.remarks || ''
    reviewForm.opinion = surveyReview.opinion || ''
    reviewForm.reviewer = surveyReview.reviewer || ''
    reviewForm.reviewDate = surveyReview.reviewDate || formatCurrentDate()
  }
}

/** 提交审核 */
const submitReview = async () => {
  try {
    const data = {
      surveyReview: {
        projectId: currentProject.value?.id,
        ...reviewForm
      }
    }

    // 调用审核提交API
    await ProjectApi.updateSurveyReview(data)
    ElMessage.success('审核提交成功')
    drawerVisible.value = false
    await getList() // 刷新列表
  } catch (error) {
    console.error('审核提交失败:', error)
    ElMessage.error('审核提交失败')
  }
}

/** 格式化当前日期 */
const formatCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
:deep(.el-tabs__nav) {
  padding: 0 10px;
}

:deep(.el-tabs__item) {
  padding: 0 9px !important;
  height: 32px;
  line-height: 32px;
  font-size: 13px;
  color: var(--el-text-color-regular);
  transition: all 0.3s;
  position: relative;

  // 添加竖线分隔符
  &:not(:last-child)::after {
    content: '';
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 1px;
    height: 14px;
    background-color: var(--el-border-color-lighter);
  }

  &.is-active {
    color: var(--el-color-primary);
    font-weight: 500;
  }

  &:hover {
    color: var(--el-color-primary);
  }
}

:deep(.el-tag) {
  margin-left: 4px;
  height: 18px;
  line-height: 18px;
  padding: 0 4px;
  border-radius: 9px;
  font-size: 11px;
  border: none;
  background-color: var(--el-color-info-light-9);

  .is-active & {
    background-color: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
  }
}

:deep(.el-tabs__active-bar) {
  height: 2px;
  border-radius: 1px;
}

// 调整布局样式
.flex {
  display: flex;
}

.h-\[calc\(100vh-100px\)\] {
  height: calc(100vh - 100px);
}

.tree-container {
  width: 260px;
  padding: 0;
}

.flex-1 {
  flex: 1;
}

.overflow-hidden {
  overflow: hidden;
}

.pl-4 {
  padding-left: 16px;
}

.pr-4 {
  padding-right: 16px;
}

.border-r {
  border-right-width: 1px;
}

.border-solid {
  border-style: solid;
}

.border-\[var\(--el-border-color-light\)\] {
  border-color: var(--el-border-color-light);
}

.flex-col {
  flex-direction: column;
}

:deep(.el-table) {
  height: 100%; // 让表格高度填充剩余空间
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #ebeef5;
  margin: 10px 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-table__header) {
  font-weight: 600;

  th {
    background-color: var(--el-table-header-bg-color);
    padding: 12px 0;
    height: 50px;
    font-size: 14px;
  }
}

:deep(.el-table__body) {
  td {
    padding: 12px 0;
    height: 56px;
  }
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto; // 表格内容可滚动
}

:deep(.el-table--striped) {
  .el-table__row--striped {
    background-color: #fafafa;
  }
}

// 表格操作按钮优化
:deep(.el-button--link) {
  padding: 4px 8px;
  border-radius: 4px;

  &:hover {
    background-color: rgba(64, 158, 255, 0.1);
  }
}

// 表格内容居中对齐
:deep(.el-table .cell) {
  padding: 0 10px;
}

.mt-4 {
  margin-top: 16px;
}

.h-full {
  height: 100%;
}

.mb-4 {
  margin-bottom: 16px;
}

/* 抽屉内容样式优化 */
.drawer-content.clear-bg {
  background: #f7f8fa;
  padding: 0 0 0 0;
}

.card-block {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
  margin-bottom: 8px;
  padding: 12px 24px 8px 24px;
}

.block-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #2d8cf0;
  margin-bottom: 1px;
  padding-bottom: 1px;
  background: none;

  .el-icon {
    margin-right: 8px;
  }
}

.info-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px 24px;
  margin-bottom: 0;
}

.info-item {
  .label {
    color: #888;
    margin-right: 6px;
    font-size: 13px;
  }

  .value {
    font-weight: 500;
    font-size: 13px;
  }
}

.review-table {
  width: 100%;
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  overflow: hidden;
  background: #fafbfc;
}

.review-table-header,
.review-table-row {
  display: flex;
  align-items: stretch;
}

.review-table-header {
  background: #f5f7fa;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e5e6eb;
}

.review-table-row:not(:last-child) {
  border-bottom: 1px solid #e5e6eb;
}

.review-table-cell {
  padding: 6px 10px;
  display: flex;
  align-items: center;
  font-size: 14px;
  background: #fff;
}

.cell-content {
  flex: 2;
  border-right: 1px solid #e5e6eb;
}

.cell-result {
  flex: 1;
  border-right: 1px solid #e5e6eb;
  justify-content: center;
}

.cell-opinion {
  flex: 2;
}

.review-textarea {
  width: 100%;
  min-height: 36px;
}

.review-result {
  margin-bottom: 6px;
}

.signature-content {
  display: flex;
  justify-content: flex-end;
  gap: 32px;
  padding: 5px 0 0 0;
}

.signature-item {
  display: flex;
  align-items: center;

  .label {
    color: #888;
    margin-right: 6px;
    font-size: 13px;
  }

  .value {
    font-weight: 500;
    font-size: 13px;
  }

  .signature-placeholder {
    min-width: 120px;
    display: inline-block;
    text-align: center;
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  padding: 22px 34px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

/* 减小签名区域与底部按钮的距离 */
.signature-section.card-block {
  padding-top: 8px;
  padding-bottom: 6px;
  margin-bottom: 0;
}

/* 添加按钮区域上方分隔线的样式 */
:deep(.el-drawer__footer) {
  padding: 0;
  border-top: none;
}
</style>
